<script setup>
import { toRefs, ref, onMounted, computed, reactive } from 'vue';
import { MoreFilled } from '@element-plus/icons-vue';
import {
  ElDropdown,
  ElIcon,
  ElMessage,
  ElTable,
  ElTableColumn,
  ElTree,
  ElDropdownMenu,
  ElDropdownItem,
} from 'element-plus';
import {
  delSystemLayerCategory,
  delSystemLayerConfig,
  getSystemLayerCategoryConfig,
  getSystemLayerCategoryList,
  postSystemLayerCategoryList,
  postSystemLayerConfig,
  putSystemLayerConfig,
} from '@/apis/api-system';
import { OPERATION_TYPE } from '@/common/js/common-const';
import ReleasePromptMessage from '@/components/ReleasePromptMessage.vue';
import { useSystemStore } from '@/stores';
import CategoryType from './CategoryType.vue';
import ReleaseOperation from './ReleaseOperation.vue';

const props = defineProps({
  name: {
    type: String,
  },
});
const { name } = toRefs(props);

const titleName = computed(() => name.value);
const systemStore = useSystemStore();

const categoryShow = ref(false);

const roles = computed(() => {
  return systemStore?.userInfo?.roles?.map((item) => {
    return item.title;
  });
});

const treeRef = ref(null);
const treeData = ref([]);
const checkedTreeItem = ref({});
const currentNodeKeyItem = ref(null);

const defaultProps = {
  id: 'id',
  children: 'children',
  label: 'title',
};

const selectParams = reactive({
  category: '',
});

const tableData = ref([]);
const operationType = ref('');
const operationShow = ref(false);
const operationData = ref({});

const defaultExpandedKeys = ref([]);

const messageInfo = reactive({
  messageBoxShow: false,
  messageText: '',
  messageBoxType: '',
});

onMounted(() => {
  getSystemLayerCategoryListApi();
});

const handleNodeClick = (item) => {
  checkedTreeItem.value = item;
  selectParams.category = item.code;

  getSystemLayerCategoryConfigApi();
};

const handleMoreTree = (type, data) => {
  operationType.value = type;

  if (type === 'EDIT') {
    categoryShow.value = true;
    operationData.value = data;
  }

  if (type == 'DEL') {
    messageInfo.infoBoxValue = data;
    messageInfo.messageBoxType = '删除';
    messageInfo.messageBoxShow = true;

    messageInfo.messageText = '该数据删除后不可恢复，确定要删除吗？';
  }
};

// 操作
const handleOperation = (type, item, val_) => {
  if (!roles.value?.some((r) => ['超级管理员', '值班人员', '运维人员']?.includes(r))) return;

  operationType.value = type;

  if (type == OPERATION_TYPE.DELETE) {
    messageInfo.infoBoxValue = item;
    messageInfo.messageBoxType = '删除';
    messageInfo.messageBoxShow = true;

    messageInfo.messageText = '该数据删除后不可恢复，确定要删除吗？';
  }

  if (type == OPERATION_TYPE.EDIT || type == OPERATION_TYPE.LOOK) {
    operationShow.value = true;
    operationData.value = item;
  }

  if (type == OPERATION_TYPE.ADD) {
    if (val_ == 'type') {
      categoryShow.value = true;
    } else {
      if (Object.keys(checkedTreeItem.value).length) {
        operationShow.value = true;
      } else {
        ElMessage.warning('请选择要配置的图层分类');
      }
    }
  }
};

const handleMessageBox = (val) => {
  messageInfo.messageBoxShow = false;
  messageInfo.messageText = '';

  if (val) {
    //  删除接口
    if (operationType.value === 'DEL') {
      delSystemLayerCategoryApi(messageInfo.infoBoxValue?.id);
    } else {
      delSystemLayerConfigApi(messageInfo.infoBoxValue?.id);
    }
  }

  messageInfo.messageBoxType = '';
};

const handleShowEmit = () => {
  operationShow.value = false;
  operationType.value = '';
  operationData.value = {};
};

// 数据
const handleParamEmit = (value, type) => {
  if (type == 'ADD') {
    postSystemLayerConfigApi(value);
  } else {
    putSystemLayerConfigApi(operationData.value?.id, value);
  }
};

const handleCategoryClose = () => {
  categoryShow.value = false;
};

const handleCategoryEmit = (val) => {
  postSystemLayerCategoryListApi(val);
};

/*
 *@description: 获取图层类型
 *@author:chen_fei
 *@Date: 2025-07-23 15:48:41
 */
const getSystemLayerCategoryListApi = async () => {
  const [err, data] = await getSystemLayerCategoryList();

  if (!err) {
    treeData.value = data.data;

    currentNodeKeyItem.value = treeData.value?.length && Number(treeData.value[0]?.id);

    checkedTreeItem.value = treeData.value?.length && treeData.value[0];

    defaultExpandedKeys.value = [treeData.value?.length && treeData.value[0]?.id, currentNodeKeyItem.value];
    treeRef.value.setCurrentKey(currentNodeKeyItem.value);

    getSystemLayerCategoryConfigApi();
  }
};

/*
 *@description: 创建/编辑图层类型
 *@author:chen_fei
 *@Date: 2025-07-23 16:25:17
 */
const postSystemLayerCategoryListApi = async (val) => {
  const [err] = await postSystemLayerCategoryList(val);

  if (!err) {
    ElMessage.success('操作成功');
    handleCategoryClose();
    getSystemLayerCategoryListApi();
  }
};

/*
 *@description: 获取列表
 *@author:chen_fei
 *@Date: 2025-07-15 14:37:10
 */
const getSystemLayerCategoryConfigApi = async () => {
  const [err, data] = await getSystemLayerCategoryConfig({
    category: checkedTreeItem.value?.code ?? '',
  });

  if (!err) {
    tableData.value = data.data;
  }
};

/*
 *@description: 新建
 *@author:chen_fei
 *@Date: 2025-07-15 14:47:20
 */
const postSystemLayerConfigApi = async (data_) => {
  const [err] = await postSystemLayerConfig(data_);

  if (!err) {
    ElMessage.success('新建成功');
  }

  getSystemLayerCategoryConfigApi();
  handleShowEmit();
};

/*
 *@description: 编辑巡护路线
 *@author:chen_fei
 *@Date: 2025-07-15 14:47:20
 */
const putSystemLayerConfigApi = async (id, data_) => {
  const [err] = await putSystemLayerConfig(id, data_);

  if (!err) {
    ElMessage.success('修改成功');
  }

  getSystemLayerCategoryConfigApi();
  handleShowEmit();
};

/*
 *@description: 删除
 *@author:chen_fei
 *@Date: 2025-07-15 14:50:14
 */
const delSystemLayerConfigApi = async (id) => {
  const [err] = await delSystemLayerConfig(id);

  if (!err) {
    ElMessage.success('删除成功');
    getSystemLayerCategoryConfigApi();
  }

  messageInfo.infoBoxValue = null;
};

/*
 *@description: 删除图层分类
 *@author:chen_fei
 *@Date: 2025-07-24 11:48:10
 */
const delSystemLayerCategoryApi = async (id) => {
  const [err] = await delSystemLayerCategory(id);

  if (!err) {
    ElMessage.success('删除成功');
    getSystemLayerCategoryListApi();
  }

  messageInfo.infoBoxValue = null;
};
</script>
<template>
  <div class="root h-100% w-100% rounded-5px p-1.5rem">
    <div class="flex-x-center">
      <div class="flex-x-center">
        <div class="left_box relative">
          <h3>图层分类</h3>
          <div
            v-if="roles.some((item) => item === '超级管理员' || item === '值班人员')"
            class="absolute right-15px top-5px flex-center cursor-pointer color-#1385cf"
            @click="handleOperation('ADD', '', 'type')"
          >
            新建分类
          </div>

          <div class="tree_box">
            <ElTree
              ref="treeRef"
              node-key="id"
              class="filter-tree"
              :data="treeData"
              :props="defaultProps"
              :highlight-current="true"
              :expand-on-click-node="false"
              :default-expanded-keys="defaultExpandedKeys"
              :current-node-key="currentNodeKeyItem"
              @node-click="handleNodeClick"
            >
              <template #default="{ node, data }">
                <span class="custom-tree-node">
                  <div class="label">
                    <p :title="`${node.label}`">{{ node.label }}</p>
                  </div>
                  <div v-if="roles.some((item) => item === '超级管理员' || item === '值班人员')">
                    <ElDropdown trigger="click">
                      <span class="el-dropdown-link">
                        <ElIcon><MoreFilled /></ElIcon>
                      </span>
                      <template #dropdown>
                        <ElDropdownMenu>
                          <ElDropdownItem @click="handleMoreTree('EDIT', data)">编辑</ElDropdownItem>
                          <hr style="border: 0; background-color: #e8e8e8; height: 1px" />
                          <ElDropdownItem @click="handleMoreTree('DEL', data)">删除</ElDropdownItem>
                        </ElDropdownMenu>
                      </template>
                    </ElDropdown>
                  </div>
                </span>
              </template>
            </ElTree>
          </div>
        </div>
      </div>
      <div class="right_box">
        <h3>{{ titleName }}</h3>
        <div class="mt-20px flex cursor-pointer items-center justify-end">
          <div
            class="btn-add flex-center"
            :class="
              roles?.some((r) => ['超级管理员', '值班人员', '运维人员']?.includes(r))
                ? 'bg-#1385cf cursor-pointer'
                : 'bg-coolgray  cursor-no-drop'
            "
            @click="handleOperation('ADD')"
          >
            新建
          </div>
        </div>
        <div class="mt-20px">
          <ElTable
            :data="tableData"
            border
            row-key="id"
            :header-cell-style="{
              color: '#333333',
              background: '#F3F3F3',
            }"
            style="width: 100%; height: 46.25rem"
          >
            <ElTableColumn prop="sortOrder" label="排序" align="center" show-overflow-tooltip />
            <ElTableColumn prop="title" label="标题" align="center" show-overflow-tooltip />

            <ElTableColumn prop="type" label="类型" align="center">
              <template #default="scope">
                <p>{{ scope.row?.type ? scope.row?.type : '--' }}</p>
              </template>
            </ElTableColumn>
            <ElTableColumn prop="layerName" label="图层名称" align="center">
              <template #default="scope">
                <p>{{ scope.row?.layerName ? scope.row?.layerName : '--' }}</p>
              </template>
            </ElTableColumn>
            <ElTableColumn prop="layerStyle" label="图层样式" align="center">
              <template #default="scope">
                <p>{{ scope.row?.layerStyle ? scope.row?.layerStyle : 'Default' }}</p>
              </template>
            </ElTableColumn>
            <ElTableColumn prop="icon" label="标识" align="center" show-overflow-tooltip>
              <template #default="scope">
                <p>{{ scope.row?.icon ? scope.row?.icon : '--' }}</p>
              </template>
            </ElTableColumn>
            <ElTableColumn prop="bbox" label="图层四至" align="center" show-overflow-tooltip>
              <template #default="scope">
                <p>{{ scope.row?.bbox ? scope.row?.bbox : '--' }}</p>
              </template>
            </ElTableColumn>
            <ElTableColumn label="操作" align="center" width="240">
              <template #default="scope">
                <div class="flex items-center justify-around">
                  <div
                    class="edit_btn flex-center"
                    :class="
                      roles?.some((r) => ['超级管理员', '值班人员', '运维人员']?.includes(r))
                        ? 'color-#1385cf cursor-pointer'
                        : 'color-coolgray  cursor-no-drop'
                    "
                    @click="handleOperation('EDIT', scope.row)"
                  >
                    编辑
                  </div>
                  <div
                    :class="
                      roles?.some((r) => ['超级管理员', '值班人员', '运维人员']?.includes(r))
                        ? 'color-#1385cf cursor-pointer'
                        : 'color-coolgray  cursor-no-drop'
                    "
                    class="look_btn flex-center"
                    @click="handleOperation('LOOK', scope.row)"
                  >
                    新增
                  </div>

                  <div
                    class="del_btn flex-center"
                    :class="
                      roles?.some((r) => ['超级管理员', '值班人员', '运维人员']?.includes(r))
                        ? 'color-#1385cf cursor-pointer'
                        : 'color-coolgray  cursor-no-drop'
                    "
                    @click="handleOperation('DELETE', scope.row)"
                  >
                    删除
                  </div>
                </div>
              </template>
            </ElTableColumn>
          </ElTable>
        </div>
      </div>
    </div>

    <!-- 提示 -->
    <ReleasePromptMessage
      v-if="messageInfo.messageBoxShow"
      :message-box-show="messageInfo.messageBoxShow"
      :message-text="messageInfo.messageText"
      :message-box-type="messageInfo.messageBoxType"
      @handle-message-box="handleMessageBox"
    />

    <!-- 图层分类 -->
    <CategoryType
      v-if="categoryShow"
      :category-show="categoryShow"
      :operation-type="operationType"
      :operation-data="operationData"
      @handle-category-close="handleCategoryClose"
      @handle-category-emit="handleCategoryEmit"
    />

    <ReleaseOperation
      v-if="operationShow"
      :operation-data="operationData"
      :operation-type="operationType"
      :operation-show="operationShow"
      :checked-tree-item="checkedTreeItem"
      @handle-param-emit="handleParamEmit"
      @handle-show-emit="handleShowEmit"
    />
  </div>
</template>

<style scoped lang="scss">
.root {
  padding: 1.5rem;
  font-size: $base-system-font-size-base;
  background-color: $base-background-white;

  .left_box {
    width: 300px;
    height: 100%;

    h3::before {
      content: '|';
      width: 4px;
      height: 30px;
      margin-right: 5px;
      color: $base-color-green;
      font-size: 18px;
      background-color: $base-color-green;
    }

    .tree_box {
      width: 100%;
      max-height: 837px;
      margin-top: 30px;
      padding-right: 20px;
      overflow: auto;

      .custom-tree-node {
        position: relative;
        display: flex;
        align-items: center;
        justify-content: space-between;
        width: 100%;
        .label {
          color: #333333;
          font-size: 18px;
          font-family: Source Han Sans CN;
        }
      }

      &::-webkit-scrollbar {
        display: none;
        width: 0 !important;
      }

      :deep(.el-tree-node__content) {
        height: 40px;
        padding-right: 9px;
        font-size: 18px;
      }

      :deep(.el-tree-node:focus > .el-tree-node__content) {
        background-color: #fff;
      }

      :deep(.el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content) {
        background-color: #f0fcf2;
      }
    }
  }
  .right_box {
    width: calc(100% - 300px);

    .edit_btn,
    .del_btn {
      font-size: $base-system-font-size-base;
    }
  }

  .btn-add {
    width: 100px;
    height: 40px;
    color: $base-button-color-white;
    border-radius: 5px;
  }
}
</style>
